package com.itcast.stargraph.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.itcast.stargraph.utils.JWTUtils;
import com.itcast.stargraph.utils.UserThreadLocalUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用户请求拦截器
 *
 * @Author katana
 * @Date 2025/6/9 15:04
 */
@Component
public class UserInterceptor implements HandlerInterceptor {
    
    
    
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1 判断目标资源如果不是自Controller方法,则放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //2 获取请求头携带的token
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StrUtil.isBlank(token)){
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }
        //3 解析token
        if (!JWTUtils.verify(token)){
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }
        //4 获取用户信息,并设置到ThreadLocal
        UserThreadLocalUtils.setUser(JWTUtils.getUser(token));
        
        //5 放行
        return true;
    }
    
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocalUtils.removeUser();//删除用户，释放内存
        
    }
}
